//
//  InputDeviceIDViewController.m
//  SqliteManagerDemo
//
//  Created by US bike on 2017/9/14.
//  Copyright © 2017年 US bike. All rights reserved.
//

#import "InputDeviceIDViewController.h"
#import "DeviceItem.h"
#import "FileManager.h"
#import "UIView+Corner.h"
#import "KiwipenEvent.h"
#import "KiwipenCommand.h"
#import "BLEManager.h"
#import "KiwipenProtocol.h"

//十六进制转UIColor
#define UIColorFromRGBA(rgbValue)  \
[UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0x0000FF))/255.0 \
alpha:1.0f]

//定义几种需要用到的颜色
#define GRAY UIColorFromRGBA(0x50514F)
#define BLUE UIColorFromRGBA(0x00AEEF)
#define YELLOW UIColorFromRGBA(0xFFE066)
#define RED UIColorFromRGBA(0xED5151)
#define GREEN UIColorFromRGBA(0x8DC63F)

#define WRITTING_TIMEOUT 5



//系统状态
typedef enum : NSUInteger {
    InputState_Init,
    InputState_Started,
    InputState_Writing,
    InputState_Stopped,
    
} InputState;

//写数据状态
typedef enum : NSUInteger {
    WriteState_Init,
    WriteState_Writing,
    WriteState_Succed,
    WriteState_Failed,
    WriteState_Complete,
} WriteState;

@interface InputDeviceIDViewController ()

@property (nonatomic, strong) NSDateFormatter *dateFormatter;

@property (nonatomic, assign) InputState currentInputState;
@property (nonatomic, assign) WriteState currentWriteState;

@property (nonatomic, strong) NSMutableArray<DeviceItem *> *recordArray;


@property (weak, nonatomic) IBOutlet UIButton *startBtn;

@property (weak, nonatomic) IBOutlet UILabel *stateLbl;

@property (weak, nonatomic) IBOutlet UILabel *recordDeviceIDLbl;
@property (weak, nonatomic) IBOutlet UILabel *receivedDeviceIDLbl;
@property (weak, nonatomic) IBOutlet UILabel *deviceUUIDLbl;
@property (weak, nonatomic) IBOutlet UILabel *progressLbl;
@property (weak, nonatomic) IBOutlet UILabel *logLbl;

//用来操作5秒内返回的block
@property (copy, nonatomic) dispatch_block_t completeAfterBlock;

@end



@implementation InputDeviceIDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    self.title = @"title";
    [self.startBtn setupCorner];
    
    self.dateFormatter = [[NSDateFormatter alloc] init];
    [self.dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
    
    //设置初始状态
    //加载数据
    [FileManager loadFileDataWithBlock:^(NSArray<DeviceItem *> *items) {
        self.recordArray = [items mutableCopy];
        self.currentInputState = InputState_Init;
        [self changeInputUIWithState:self.currentInputState];
        self.currentWriteState = WriteState_Init;
        [self updateWriteUIWithState:self.currentWriteState];

    }];
    
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithBLEConnected:) name:BLEConnectedNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithBLEReceivedDeviceID:) name:UUIDNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dealWithBLECompleted) name:BLEDisconnectedNotification object:nil];
    
}


- (void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - 更新操作状态
- (void) changeInputStateFromState:(InputState) fromState ToState:(InputState) toState{
    
    
    self.currentInputState = toState;
    [self changeInputUIWithState:toState];
    
    
    switch (fromState) {
        case InputState_Init:
            
            if (InputState_Started == toState) {
                NSLog(@"加载文件，并开始搜索蓝牙");
                if ([self invalidateData]) {
                    [self startWrittingDeviceId];
                } else {
                    [self changeInputStateFromState:self.currentInputState ToState:InputState_Stopped];
                }
            }
            break;
        case InputState_Started:
            if (InputState_Writing == toState) {
                NSLog(@"蓝牙已连接");
            }
            break;
            
            
        case InputState_Writing:
            if (InputState_Stopped == toState) {
                
                //保存到文件中
                [FileManager saveFileWithArray:self.recordArray WithBlock:^{
                    NSLog(@"文件已保存");
                }];
            }
            break;
            
        case InputState_Stopped:
            if (InputState_Started == toState) {
                NSLog(@"开始搜索蓝牙");
                if ([self invalidateData]) {
                    [self startWrittingDeviceId];
                } else {
                    [self changeInputStateFromState:self.currentInputState ToState:InputState_Stopped];
                }
            }
            break;
            
        default:
            break;
    }
    
}

#pragma mark - 更新控制按钮状态
- (void) changeInputUIWithState:(InputState) inputState {
    
    [self updateProgressUI];
    switch (inputState) {
        case InputState_Init:
            
            [self.startBtn setEnabled:YES];
            self.stateLbl.text = @"init";
            
            break;
            
        case InputState_Started:
            
            [self.startBtn setEnabled:NO];
            self.stateLbl.text = @"started";
            
            
            break;
            
        case InputState_Stopped:
            
            [self.startBtn setEnabled:YES];
            self.stateLbl.text = @"stop";
            
            break;
            
        case InputState_Writing:
            
            [self.startBtn setEnabled:NO];
            self.stateLbl.text = @"writing";
            
            break;
        default:
            break;
    }
}




#pragma mark - 更新写入deviceId的状态
//更新待写入deviceID标签
- (void) updateWriteFrom:(WriteState) fromState To:(WriteState) toState {
    
    self.currentWriteState = toState;
    [self updateWriteUIWithState:self.currentWriteState];
    
    switch (fromState) {
        case WriteState_Init:
            
            if (WriteState_Writing == toState) {
                
                self.recordDeviceIDLbl.text = [NSString stringWithFormat:@"  待写入deviceId:\n  %@", [self getCurrentDeviceItem].deviceID];
                self.receivedDeviceIDLbl.text = @"  返回的deviceId:\n";
                self.deviceUUIDLbl.text = @"  设备地址：\n";
                
                //更新系统状态
                [self changeInputStateFromState:self.currentInputState ToState:InputState_Writing];
            }
            
            break;
        case WriteState_Writing:
            if (WriteState_Succed == toState) {
                DeviceItem *item = [self getCurrentDeviceItem];
                item.update = [self.dateFormatter stringFromDate:[NSDate date]];
                item.recordState = RecordState_WRITE_SUCCEED;
                
            } else if (WriteState_Failed == toState) {
                DeviceItem *item = [self getCurrentDeviceItem];
                item.update = [self.dateFormatter stringFromDate:[NSDate date]];
                item.recordState = RecordState_WRITE_FAILED;
            }
            
            break;
        case WriteState_Succed:
            if (WriteState_Complete == toState) {
                [self changeInputStateFromState:self.currentInputState ToState:InputState_Stopped];
            }
            
            break;
        case WriteState_Failed:
            if (WriteState_Complete == toState) {
                [self changeInputStateFromState:self.currentInputState ToState:InputState_Stopped];
            }
            
            break;
        case WriteState_Complete:
            
            if (WriteState_Init == toState) {
                self.recordDeviceIDLbl.text = [NSString stringWithFormat:@"  待写入deviceId:\n  %@", [self getCurrentDeviceItem].deviceID];
                self.receivedDeviceIDLbl.text = @"  返回的deviceId:\n";
                self.deviceUUIDLbl.text = @"  设备地址:\n";
                
            } else if (WriteState_Writing == toState) {
                
                //更新系统状态
                [self changeInputStateFromState:self.currentInputState ToState:InputState_Writing];
                
            }
            break;
            
        default:
            break;
    }
}

- (void) updateWriteUIWithState:(WriteState) state {
    
    switch (state) {
        case WriteState_Init:
            self.recordDeviceIDLbl.text = [NSString stringWithFormat:@"  待写入deviceId:\n  %@", [self getCurrentDeviceItem].deviceID];
            self.receivedDeviceIDLbl.text = @"  返回的deviceId:\n";
            self.deviceUUIDLbl.text = @"  设备地址:\n";
            self.recordDeviceIDLbl.backgroundColor = BLUE;
            
            break;
            
        case WriteState_Writing:
            self.recordDeviceIDLbl.backgroundColor = YELLOW;
            break;
            
        case WriteState_Succed:
            self.recordDeviceIDLbl.backgroundColor = GREEN;
            break;
            
        case WriteState_Failed:
            self.recordDeviceIDLbl.backgroundColor = RED;
            break;
            
        case WriteState_Complete:
            //self.recordDeviceIDLbl.backgroundColor = BLUE;
            break;
            
        default:
            break;
    }
    
}

- (void) updateProgressUI {
    //获取已经写入的数据个数
    NSUInteger writtenCount = self.recordArray.count;
    for (DeviceItem *item in self.recordArray) {
        if (item.recordState == RecordState_UNWRITEN){
            writtenCount = [self.recordArray indexOfObject:item];
            break;
        }
    }
    
    //更新进度标签
    self.progressLbl.text = [NSString stringWithFormat:@"%ld    /    %ld", (long)writtenCount, (long)self.recordArray.count];
}



- (DeviceItem *) getCurrentDeviceItem {
    for (DeviceItem *item in self.recordArray) {
        if (item.recordState == RecordState_UNWRITEN){
            return item;
        }
    }
    return nil;
}

//判断是否还有未录入的数据
- (Boolean) invalidateData {
    if ([self getCurrentDeviceItem]) {
        return YES;
    } else {
        
        NSLog(@"所有数据都已经写完");
        
        UIAlertController *vc = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"所有deviceId已经写完" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [vc addAction:action];
        [self presentViewController:vc animated:YES completion:nil];
        
        return NO;
    }
}

#pragma mark - 开始蓝牙操作
//开始执行蓝牙操作
- (void) startWrittingDeviceId {
    
    //初始化写入状态空间
    [self updateWriteFrom:self.currentWriteState To:WriteState_Init];
    
    //开始搜索并连接蓝牙设备
    [[BLEManager shareBLEManager] scanPeripheralsWithSearchType:SearchTypeAll SearchBlock:^(BOOL success, NSArray<CBPeripheral *> *peripheralList) {
        if (success) {
            
            CBPeripheral *peripheral = [peripheralList objectAtIndex:0];
            [[BLEManager shareBLEManager] connectWithPeripheral:peripheral AndConnectBlock:nil];
        } else {
            NSLog(@"未搜索到符合条件的蓝牙设备！！！  这里应该永远不执行，因为搜索没有超时");
        }
    }];
    
    //self.logLbl.text = @"正在搜索蓝牙设备...";
    
}


#pragma mark - 按钮点击事件
- (IBAction)startAction:(id)sender {
    [self changeInputStateFromState:self.currentInputState ToState:InputState_Started];
    
}


#pragma mark - Notifi

//蓝牙已经连接 --  表示已经进入writing状态
- (void) dealWithBLEConnected:(NSNotification *) notifi  {
    NSLog(@"dealWithBLEConnected");
    NSString * uuidStr = notifi.object;
    
    //更新写入状态和UI
    [self updateWriteFrom:self.currentWriteState To:WriteState_Writing];
    
    //更新UUID
    [self getCurrentDeviceItem].address = uuidStr;
    self.deviceUUIDLbl.text = [NSString stringWithFormat:@"  设备地址:\n  %@",uuidStr];
    
    //写入数据
    KiwipenCommand *cmd = [KiwipenCommand CreateCommondWitCommandType:CommandTypeWriteUUID AndDeviceIdStr:[self getCurrentDeviceItem].deviceID];
    [[BLEManager shareBLEManager] writeDataWithData:cmd.commandData];
    
    
    //准备超时之后执行的任务
    self.completeAfterBlock = dispatch_block_create(DISPATCH_BLOCK_BARRIER, ^{
        //写操作未完成
        if (self.currentInputState == InputState_Writing && self.currentWriteState == WriteState_Writing) {
            
            [[BLEManager shareBLEManager] cancelAll];
        }
        
    });
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(WRITTING_TIMEOUT * NSEC_PER_SEC)), dispatch_get_main_queue(), self.completeAfterBlock);
    
    
}

//蓝牙收到id
- (void) dealWithBLEReceivedDeviceID:(NSNotification *) notifi {
    NSLog(@"dealWithBLEReceivedDeviceID");
    
    NSString * deviceId = notifi.object;
    
    self.receivedDeviceIDLbl.text = [NSString stringWithFormat:@"  返回的deviceId:\n  %@",deviceId];
    
    
    //比较deviceId是否一致
    if ([deviceId isEqualToString:[self getCurrentDeviceItem].deviceID]) {
        NSLog(@"deviceId写入成功");
        [self updateWriteFrom:self.currentWriteState To:WriteState_Succed];
        
    } else {
        NSLog(@"deviceId写入失败");
        [self updateWriteFrom:self.currentWriteState To:WriteState_Failed];
    }
    
    [[BLEManager shareBLEManager] cancelAll];
    dispatch_cancel(self.completeAfterBlock);

    
}

//蓝牙断开连接 --  表示已经完成一次写操作，判断写入结果并更新UI，重新进入start状态
- (void) dealWithBLECompleted {
    //更新写入状态和UI
    NSLog(@"dealWithBLECompleted");
    
    if (self.currentWriteState == WriteState_Writing) {
        [self updateWriteFrom:self.currentWriteState To:WriteState_Failed];
    }
    
    [self updateWriteFrom:self.currentWriteState To:WriteState_Complete];
}

//处理屏幕旋转
-(UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    
    return UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortrait;
}

-(BOOL)shouldAutorotate
{
    
    return YES;
}


- (void) viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    
}

- (void) viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}


- (BOOL)prefersStatusBarHidden
{
    return NO;
}
@end
